package com.fzh.service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServerReadThread extends Thread{
    private final Socket socket;

    public ServerReadThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run(){
        try {
            InputStream is=socket.getInputStream();
            DataInputStream dis =new DataInputStream(is);
            while(true){
                try{
                    String msg= dis.readUTF();
                    System.out.println(msg);
                    SendMsgToAll(msg);
                }catch (Exception e){
                    System.out.println("用户下线了");
                    server.onLineSockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void SendMsgToAll(String msg) throws IOException {
        for(Socket onLineSockets :server.onLineSockets){

            OutputStream os = socket.getOutputStream();

            DataOutputStream dos = new DataOutputStream(os);

            dos.writeUTF(msg);

            dos.flush();

        }
    }

}
